<template>
  <div class="maintenance-records">
    <div class="page-header">
      <h2>维修记录</h2>
      <Button type="primary" @click="exportRecords">
        <IconifyIcon icon="ant-design:download-outlined" />
        导出记录
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总维修数"
          :value="statistics.totalRecords"
          :change="statistics.totalChange"
          icon="ant-design:tool-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="本月维修"
          :value="statistics.monthlyRecords"
          :change="statistics.monthlyChange"
          icon="ant-design:calendar-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均耗时"
          :value="statistics.averageTime"
          :change="statistics.timeChange"
          icon="ant-design:clock-circle-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="维修成本"
          :value="statistics.totalCost"
          :change="statistics.costChange"
          icon="ant-design:dollar-outlined"
          color="#f5222d"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <FormItem label="工单号">
          <Input
            v-model:value="searchForm.workOrderNumber"
            placeholder="请输入工单号"
            allow-clear
          />
        </FormItem>
        <FormItem label="房间号">
          <Input
            v-model:value="searchForm.roomNumber"
            placeholder="请输入房间号"
            allow-clear
          />
        </FormItem>
        <FormItem label="维修类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择类型"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="electrical">电气维修</SelectOption>
            <SelectOption value="plumbing">水管维修</SelectOption>
            <SelectOption value="appliance">家电维修</SelectOption>
            <SelectOption value="furniture">家具维修</SelectOption>
            <SelectOption value="structural">结构维修</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="维修人员">
          <Input
            v-model:value="searchForm.technician"
            placeholder="请输入维修人员"
            allow-clear
          />
        </FormItem>
        <FormItem label="完成状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="completed">已完成</SelectOption>
            <SelectOption value="cancelled">已取消</SelectOption>
            <SelectOption value="in_progress">进行中</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="完成日期">
          <DatePicker
            v-model:value="searchForm.completionDate"
            placeholder="选择日期"
            style="width: 150px"
          />
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 维修趋势图 -->
    <Card title="维修趋势" class="chart-card">
      <div class="chart-container">
        <div class="chart-placeholder">
          <IconifyIcon
            icon="ant-design:line-chart-outlined"
            class="chart-icon"
          />
          <p>维修数量趋势图表</p>
          <p class="chart-desc">显示最近12个月的维修数量变化趋势</p>
        </div>
      </div>
    </Card>

    <!-- 维修记录表格 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredRecords"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'workOrderNumber'">
            <Button type="link" @click="viewWorkOrderDetail(record)">
              {{ record.workOrderNumber }}
            </Button>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'duration'">
            <span class="duration-text">{{ record.duration }}</span>
          </template>
          <template v-else-if="column.key === 'cost'">
            <span class="cost-text">¥{{ record.cost }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                查看详情
              </Button>
              <Button
                type="link"
                size="small"
                @click="viewQualityInspection(record)"
              >
                质量检查
              </Button>
              <Button type="link" size="small" @click="downloadReport(record)">
                下载报告
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 记录详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="维修记录详情"
      width="900px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="工单号">
          {{ selectedRecord?.workOrderNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="房间号">
          {{ selectedRecord?.roomNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="维修类型">
          <Tag :color="getTypeColor(selectedRecord?.type)">
            {{ getTypeText(selectedRecord?.type) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="优先级">
          <Tag :color="getPriorityColor(selectedRecord?.priority)">
            {{ getPriorityText(selectedRecord?.priority) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="维修人员">
          {{ selectedRecord?.technician }}
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedRecord?.technicianPhone }}
        </DescriptionsItem>
        <DescriptionsItem label="报修时间">
          {{ selectedRecord?.reportTime }}
        </DescriptionsItem>
        <DescriptionsItem label="开始时间">
          {{ selectedRecord?.startTime }}
        </DescriptionsItem>
        <DescriptionsItem label="完成时间">
          {{ selectedRecord?.completionTime }}
        </DescriptionsItem>
        <DescriptionsItem label="维修耗时">
          {{ selectedRecord?.duration }}
        </DescriptionsItem>
        <DescriptionsItem label="维修状态">
          <Tag :color="getStatusColor(selectedRecord?.status)">
            {{ getStatusText(selectedRecord?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="维修成本">
          ¥{{ selectedRecord?.cost }}
        </DescriptionsItem>
        <DescriptionsItem label="问题描述" :span="2">
          {{ selectedRecord?.description }}
        </DescriptionsItem>
        <DescriptionsItem label="维修过程" :span="2">
          <div class="process-timeline">
            <Timeline>
              <TimelineItem
                v-for="(step, index) in selectedRecord?.process"
                :key="index"
                :color="step.color"
              >
                <div class="timeline-content">
                  <div class="timeline-time">{{ step.time }}</div>
                  <div class="timeline-title">{{ step.title }}</div>
                  <div class="timeline-desc">{{ step.description }}</div>
                </div>
              </TimelineItem>
            </Timeline>
          </div>
        </DescriptionsItem>
        <DescriptionsItem label="使用配件" :span="2">
          <div class="parts-list">
            <div
              v-for="part in selectedRecord?.parts"
              :key="part.name"
              class="part-item"
            >
              <span class="part-name">{{ part.name }}</span>
              <span class="part-quantity">x{{ part.quantity }}</span>
              <span class="part-price">¥{{ part.price }}</span>
            </div>
          </div>
        </DescriptionsItem>
        <DescriptionsItem label="维修结果" :span="2">
          {{ selectedRecord?.result }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedRecord?.remarks || '无' }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 质量检查弹窗 -->
    <Modal
      v-model:open="showQualityModal"
      title="质量检查记录"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedQualityInspection">
        <Descriptions :column="2" bordered>
          <DescriptionsItem label="检查人员">
            {{ selectedQualityInspection.inspector }}
          </DescriptionsItem>
          <DescriptionsItem label="检查日期">
            {{ selectedQualityInspection.inspectionDate }}
          </DescriptionsItem>
          <DescriptionsItem label="检查结果">
            <Tag :color="getResultColor(selectedQualityInspection.result)">
              {{ getResultText(selectedQualityInspection.result) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="评分">
            {{ selectedQualityInspection.score }}/100
          </DescriptionsItem>
          <DescriptionsItem label="检查项目" :span="2">
            <div class="inspection-items">
              <div
                v-for="item in selectedQualityInspection.items"
                :key="item.name"
                class="inspection-item"
              >
                <span class="item-name">{{ item.name }}</span>
                <Tag :color="item.passed ? 'green' : 'red'">
                  {{ item.passed ? '通过' : '不通过' }}
                </Tag>
                <span class="item-score">{{ item.score }}分</span>
              </div>
            </div>
          </DescriptionsItem>
          <DescriptionsItem label="检查意见" :span="2">
            {{ selectedQualityInspection.comments }}
          </DescriptionsItem>
          <DescriptionsItem label="改进建议" :span="2">
            {{ selectedQualityInspection.suggestions }}
          </DescriptionsItem>
        </Descriptions>
      </div>
      <div v-else class="no-quality-inspection">
        <IconifyIcon
          icon="ant-design:info-circle-outlined"
          class="no-data-icon"
        />
        <p>暂无质量检查记录</p>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Timeline,
  TimelineItem,
} from 'ant-design-vue';
import dayjs from 'dayjs';

// 状态管理
const loading = ref(false);
const showDetailModal = ref(false);
const showQualityModal = ref(false);
const selectedRecord = ref(null);
const selectedQualityInspection = ref(null);

// 统计数据
const statistics = reactive({
  totalRecords: 234,
  totalChange: 12,
  monthlyRecords: 28,
  monthlyChange: 5,
  averageTime: '2.5小时',
  timeChange: -0.3,
  totalCost: '12,450',
  costChange: 8.5,
});

// 搜索表单
const searchForm = reactive({
  workOrderNumber: '',
  roomNumber: '',
  type: '',
  technician: '',
  status: '',
  completionDate: null,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 维修记录数据
const records = ref([
  {
    id: 1,
    workOrderNumber: 'WO-2024-001',
    roomNumber: '101',
    type: 'electrical',
    priority: 'high',
    technician: '张师傅',
    technicianPhone: '13800138001',
    reportTime: '2024-01-15 09:30',
    startTime: '2024-01-15 10:00',
    completionTime: '2024-01-15 12:30',
    duration: '2.5小时',
    status: 'completed',
    cost: 350,
    description: '房间插座无电，经检查发现线路老化导致短路',
    process: [
      {
        time: '10:00',
        title: '到达现场',
        description: '维修人员到达房间，开始检查问题',
        color: 'blue',
      },
      {
        time: '10:15',
        title: '问题诊断',
        description: '发现插座线路老化，存在安全隐患',
        color: 'orange',
      },
      {
        time: '11:00',
        title: '更换线路',
        description: '更换老化线路，确保安全',
        color: 'green',
      },
      {
        time: '12:30',
        title: '测试完成',
        description: '测试插座功能正常，维修完成',
        color: 'green',
      },
    ],
    parts: [
      { name: '电线', quantity: 5, price: 50 },
      { name: '插座', quantity: 2, price: 80 },
      { name: '开关', quantity: 1, price: 30 },
    ],
    result: '插座功能恢复正常，安全隐患已消除',
    remarks: '建议定期检查线路老化情况',
  },
  {
    id: 2,
    workOrderNumber: 'WO-2024-002',
    roomNumber: '205',
    type: 'plumbing',
    priority: 'medium',
    technician: '李师傅',
    technicianPhone: '13800138002',
    reportTime: '2024-01-14 14:20',
    startTime: '2024-01-14 15:00',
    completionTime: '2024-01-14 16:30',
    duration: '1.5小时',
    status: 'completed',
    cost: 200,
    description: '卫生间水龙头漏水，需要更换密封圈',
    process: [
      {
        time: '15:00',
        title: '到达现场',
        description: '维修人员到达房间',
        color: 'blue',
      },
      {
        time: '15:10',
        title: '检查问题',
        description: '发现水龙头密封圈损坏',
        color: 'orange',
      },
      {
        time: '16:00',
        title: '更换配件',
        description: '更换新的密封圈',
        color: 'green',
      },
      {
        time: '16:30',
        title: '测试完成',
        description: '测试水龙头无漏水，维修完成',
        color: 'green',
      },
    ],
    parts: [
      { name: '密封圈', quantity: 1, price: 15 },
      { name: '生料带', quantity: 1, price: 5 },
    ],
    result: '水龙头漏水问题已解决',
    remarks: '无',
  },
  {
    id: 3,
    workOrderNumber: 'WO-2024-003',
    roomNumber: '302',
    type: 'appliance',
    priority: 'low',
    technician: '王师傅',
    technicianPhone: '13800138003',
    reportTime: '2024-01-13 16:00',
    startTime: '2024-01-13 16:30',
    completionTime: '2024-01-13 17:00',
    duration: '0.5小时',
    status: 'completed',
    cost: 80,
    description: '空调遥控器无法使用，电池接触不良',
    process: [
      {
        time: '16:30',
        title: '到达现场',
        description: '维修人员到达房间',
        color: 'blue',
      },
      {
        time: '16:35',
        title: '检查问题',
        description: '发现电池接触点氧化',
        color: 'orange',
      },
      {
        time: '16:50',
        title: '清洁修复',
        description: '清洁电池接触点，修复接触不良',
        color: 'green',
      },
      {
        time: '17:00',
        title: '测试完成',
        description: '遥控器功能正常，维修完成',
        color: 'green',
      },
    ],
    parts: [{ name: '电池', quantity: 2, price: 10 }],
    result: '遥控器功能恢复正常',
    remarks: '建议定期更换电池',
  },
]);

// 质量检查数据
const qualityInspections = ref([
  {
    workOrderNumber: 'WO-2024-001',
    inspector: '张主管',
    inspectionDate: '2024-01-15 13:00',
    result: 'pass',
    score: 92,
    items: [
      { name: '维修质量', passed: true, score: 28 },
      { name: '安全标准', passed: true, score: 24 },
      { name: '现场清洁', passed: true, score: 18 },
      { name: '文档完整', passed: true, score: 14 },
      { name: '客户满意度', passed: true, score: 8 },
    ],
    comments: '整体维修质量良好，符合标准要求',
    suggestions: '建议加强现场清洁管理',
  },
  {
    workOrderNumber: 'WO-2024-002',
    inspector: '李经理',
    inspectionDate: '2024-01-14 17:00',
    result: 'pass',
    score: 88,
    items: [
      { name: '维修质量', passed: true, score: 26 },
      { name: '安全标准', passed: true, score: 23 },
      { name: '现场清洁', passed: true, score: 17 },
      { name: '文档完整', passed: true, score: 13 },
      { name: '客户满意度', passed: true, score: 9 },
    ],
    comments: '维修工作完成度较高',
    suggestions: '无',
  },
]);

// 表格列定义
const columns = [
  {
    title: '工单号',
    dataIndex: 'workOrderNumber',
    key: 'workOrderNumber',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '维修类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 80,
  },
  {
    title: '维修人员',
    dataIndex: 'technician',
    key: 'technician',
    width: 100,
  },
  {
    title: '完成时间',
    dataIndex: 'completionTime',
    key: 'completionTime',
    width: 150,
  },
  {
    title: '维修耗时',
    dataIndex: 'duration',
    key: 'duration',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '维修成本',
    dataIndex: 'cost',
    key: 'cost',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 过滤后的记录数据
const filteredRecords = computed(() => {
  let result = records.value;

  if (searchForm.workOrderNumber) {
    result = result.filter((item) =>
      item.workOrderNumber
        .toLowerCase()
        .includes(searchForm.workOrderNumber.toLowerCase()),
    );
  }

  if (searchForm.roomNumber) {
    result = result.filter((item) =>
      item.roomNumber
        .toLowerCase()
        .includes(searchForm.roomNumber.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.technician) {
    result = result.filter((item) =>
      item.technician
        .toLowerCase()
        .includes(searchForm.technician.toLowerCase()),
    );
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.completionDate) {
    result = result.filter((item) =>
      item.completionTime.includes(searchForm.completionDate),
    );
  }

  return result;
});

// 类型相关函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    electrical: 'blue',
    plumbing: 'cyan',
    appliance: 'green',
    furniture: 'orange',
    structural: 'red',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    electrical: '电气维修',
    plumbing: '水管维修',
    appliance: '家电维修',
    furniture: '家具维修',
    structural: '结构维修',
  };
  return texts[type] || type;
};

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    completed: 'green',
    cancelled: 'red',
    in_progress: 'blue',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    completed: '已完成',
    cancelled: '已取消',
    in_progress: '进行中',
  };
  return texts[status] || status;
};

// 优先级相关函数
const getPriorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    low: 'green',
    medium: 'blue',
    high: 'orange',
    urgent: 'red',
  };
  return colors[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
  };
  return texts[priority] || priority;
};

// 质量检查相关函数
const getResultColor = (result: string) => {
  const colors: Record<string, string> = {
    pass: 'green',
    fail: 'red',
  };
  return colors[result] || 'default';
};

const getResultText = (result: string) => {
  const texts: Record<string, string> = {
    pass: '通过',
    fail: '不通过',
  };
  return texts[result] || result;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    workOrderNumber: '',
    roomNumber: '',
    type: '',
    technician: '',
    status: '',
    completionDate: null,
  });
  pagination.current = 1;
  message.success('重置完成');
};

const viewDetail = (record: any) => {
  selectedRecord.value = record;
  showDetailModal.value = true;
};

const viewQualityInspection = (record: any) => {
  const inspection = qualityInspections.value.find(
    (item) => item.workOrderNumber === record.workOrderNumber,
  );
  selectedQualityInspection.value = inspection || null;
  showQualityModal.value = true;
};

const viewWorkOrderDetail = (record: any) => {
  message.info(`查看工单详情: ${record.workOrderNumber}`);
};

const downloadReport = (record: any) => {
  message.success(`下载维修报告: ${record.workOrderNumber}`);
};

const exportRecords = () => {
  message.success('维修记录导出成功');
};

onMounted(() => {
  // 初始化数据
  pagination.total = records.value.length;
});
</script>

<style scoped>
.maintenance-records {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.chart-card {
  margin-bottom: 16px;
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.chart-placeholder {
  color: #999;
  text-align: center;
}

.chart-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.chart-desc {
  margin-top: 8px;
  font-size: 14px;
}

.table-card {
  margin-bottom: 16px;
}

.duration-text {
  font-weight: 500;
  color: #1890ff;
}

.cost-text {
  font-weight: 500;
  color: #f5222d;
}

.process-timeline {
  margin-top: 16px;
}

.timeline-content {
  margin-left: 8px;
}

.timeline-time {
  margin-bottom: 4px;
  font-size: 12px;
  color: #999;
}

.timeline-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.timeline-desc {
  font-size: 14px;
  color: #666;
}

.parts-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.part-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.part-name {
  flex: 1;
  font-weight: 500;
}

.part-quantity {
  font-weight: 500;
  color: #1890ff;
}

.part-price {
  font-weight: 500;
  color: #f5222d;
}

.inspection-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.inspection-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.item-name {
  min-width: 80px;
  font-weight: 500;
}

.item-score {
  font-weight: 500;
  color: #1890ff;
}

.no-quality-inspection {
  padding: 40px;
  color: #999;
  text-align: center;
}

.no-data-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: 500;
}
</style>
